<template>
    <div class="wifi-upload">
        <div class="upload-container">
            <div class="avatar-section">
                <img src="/images/mine/ai-avatar.png" alt="AI头像" class="avatar" />
                <h2>Hi, 我是橙子！请拖拽或点击上传简历</h2>
                <p class="subtitle">简历建议使用 PDF文件，也支持DOC、DOCX、JPEG、PNG等格式，大小不超过20M</p>
            </div>

            <div class="upload-area" @dragenter.prevent="onDragEnter" @dragover.prevent="onDragOver"
                @dragleave.prevent="onDragLeave" @drop.prevent="onDrop" :class="{ 'dragging': isDragging }">
                <input type="file" ref="fileInput" class="file-input" @change="handleFileChange"
                    accept=".pdf,.doc,.docx,.jpeg,.jpg,.png" hidden />
                <div class="upload-content" @click="triggerFileInput">
                    <van-icon name="plus" class="upload-icon" />
                    <p class="upload-text">点击或拖拽文件到这里上传</p>
                    <p class="upload-tip">支持 PDF、DOC、DOCX、JPEG、PNG 等格式</p>
                </div>
            </div>

            <div class="file-list" v-if="currentFile">
                <div class="file-item">
                    <div class="file-info">
                        <van-icon name="description" class="file-icon" />
                        <div class="file-details">
                            <span class="file-name">{{ currentFile.name }}</span>
                            <span class="file-size">{{ formatFileSize(currentFile.size) }}</span>
                        </div>
                    </div>

                    <div class="file-actions">
                        <div class="file-status">
                            <template v-if="currentFile.status === 'uploading'">
                                <van-loading type="spinner" size="16" />
                                <span class="status-text">上传中...</span>
                            </template>
                            <template v-else-if="currentFile.status === 'success'">
                                <van-icon name="success" class="success-icon" />
                                <span class="status-text">上传成功</span>
                            </template>
                            <template v-else-if="currentFile.status === 'error'">
                                <van-icon name="cross" class="error-icon" />
                                <span class="status-text">上传失败</span>
                            </template>
                        </div>
                        <div class="action-buttons">
                            <van-button v-if="currentFile.status === 'error'" size="small" type="primary"
                                @click="triggerFileInput">重新上传</van-button>
                            <van-button v-else-if="currentFile.status === 'success'" size="small" plain
                                @click="triggerFileInput">更换简历</van-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, onMounted, onBeforeUnmount } from 'vue'
    import { showToast } from 'vant'
    import { uploadFiles } from '@/api/comm'
    import { resumeApi } from '@/api/resume'
    import NavBar from '@/components/NavBar/index.vue'
    import { useRoute } from 'vue-router'
    import emitter from '@/utils/eventBus'
    const router = useRoute()
    const isDragging = ref(false)
    const fileInput = ref(null)
    const currentFile = ref(null)
    const linkToken = ref()

    // 触发文件选择
    const triggerFileInput = () => {
        fileInput.value.click()
    }

    // 处理文件大小格式化
    const formatFileSize = (bytes) => {
        if (bytes === 0) return '0 B'
        const k = 1024
        const sizes = ['B', 'KB', 'MB', 'GB']
        const i = Math.floor(Math.log(bytes) / Math.log(k))
        return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`
    }

    // 处理文件选择
    const handleFileChange = (event) => {
        const files = event.target.files
        if (files.length > 0) {
            handleFiles(Array.from(files))
        }
        // 清空 input 值，确保同一文件可以重复选择
        event.target.value = ''
    }

    // 拖拽相关处理
    const onDragEnter = () => {
        isDragging.value = true
    }

    const onDragOver = () => {
        isDragging.value = true
    }

    const onDragLeave = () => {
        isDragging.value = false
    }

    const onDrop = (event) => {
        isDragging.value = false
        const files = event.dataTransfer.files
        if (files.length > 0) {
            handleFiles(Array.from(files))
        }
    }

    // 处理文件上传
    const handleFiles = async (files) => {
        const file = files[0] // 只处理第一个文件

        // 检查文件大小
        if (file.size > 20 * 1024 * 1024) {
            showToast('文件大小不能超过20M')
            return
        }

        // 检查文件类型
        const allowedTypes = ['.pdf', '.doc', '.docx', '.jpeg', '.jpg', '.png']
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase()
        if (!allowedTypes.includes(fileExtension)) {
            showToast('不支持的文件格式')
            return
        }

        // 更新当前文件状态
        currentFile.value = {
            name: file.name,
            size: file.size,
            status: 'uploading'
        }

        try {
            // 上传文件
            const uploadRes = await uploadFiles(file)
            console.log('上传结果:', uploadRes)

            if (uploadRes.code === 0) {
                try {
                    // 创建简历记录
                    const pcRes = await resumeApi.uploadPc({
                        token: linkToken.value,
                        cv_name: file.name,
                        cv_url: uploadRes.data.url
                    })

                    if (pcRes.code === 0) {
                        currentFile.value.status = 'success'
                        emitter.emit('resume-file-upload', file)
                        showToast('上传成功')
                        // 延迟返回
                        setTimeout(() => {
                            window.close()
                        }, 1000)
                    } else {
                        currentFile.value.status = 'error'
                        showToast(pcRes.msg)
                    }
                } catch (pcError) {
                    console.error('创建简历记录失败:', pcError)
                    currentFile.value.status = 'error'
                }
            } else {
                currentFile.value.status = 'error'
                showToast(uploadRes.msg || '上传失败')
            }
        } catch (error) {
            console.error('上传文件失败:', error)
            currentFile.value.status = 'error'
            showToast('上传失败，请重试')
        }
    }

    onMounted(() => {
        // 获取链接token
        console.log('路由查询参数:', router.query)
        if (router.query && router.query.token) {
            linkToken.value = router.query.token
        }
    })
</script>

<style lang="scss" scoped>
    .wifi-upload {
        min-height: 100vh;
        background: #fff;
        padding: 16px;

        @media screen and (min-width: 768px) {
            padding: 24px;
            background: #f5f6f7;
        }

        .upload-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 24px;
            text-align: center;

            @media screen and (min-width: 768px) {
                padding: 32px;
                background: #fff;
                border-radius: 16px;
                box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            }

            .avatar-section {
                margin-bottom: 24px;

                @media screen and (min-width: 768px) {
                    margin-bottom: 32px;
                }

                .avatar {
                    width: 80px;
                    height: 80px;
                    border-radius: 60px;
                    margin-bottom: 20px;

                    @media screen and (min-width: 768px) {
                        width: 100px;
                        height: 100px;
                    }
                }

                h2 {
                    font-size: 20px;
                    color: #333;
                    margin-bottom: 12px;

                    @media screen and (min-width: 768px) {
                        font-size: 22px;
                    }
                }

                .subtitle {
                    font-size: 14px;
                    color: #666;

                    @media screen and (min-width: 768px) {
                        font-size: 15px;
                    }
                }
            }

            .upload-area {
                border: 2px dashed #dcdee0;
                border-radius: 8px;
                padding: 16px;
                margin: 0 auto 20px;
                transition: all 0.3s;
                cursor: pointer;
                max-width: 400px;

                &.dragging {
                    border-color: #165dff;
                    background-color: rgba(22, 93, 255, 0.05);
                }

                &:hover {
                    border-color: #165dff;
                }

                .upload-content {
                    .upload-icon {
                        font-size: 24px;
                        color: #165dff;
                        margin-bottom: 8px;
                    }

                    .upload-text {
                        font-size: 14px;
                        color: #333;
                        margin-bottom: 4px;
                    }

                    .upload-tip {
                        font-size: 12px;
                        color: #999;
                    }
                }
            }

            .file-list {
                max-width: 400px;
                margin: 0 auto;

                .file-item {
                    background: #f5f6f7;
                    border-radius: 8px;
                    padding: 12px;
                    margin-bottom: 12px;

                    .file-info {
                        display: flex;
                        align-items: flex-start;
                        margin-bottom: 8px;

                        .file-icon {
                            font-size: 20px;
                            color: #165dff;
                            margin-right: 8px;
                            margin-top: 2px;
                        }

                        .file-details {
                            display: flex;
                            flex-direction: column;
                            align-items: flex-start;
                            flex: 1;
                            overflow: hidden;

                            .file-name {
                                font-size: 14px;
                                color: #333;
                                margin-bottom: 2px;
                                word-break: break-all;
                            }

                            .file-size {
                                font-size: 12px;
                                color: #999;
                            }
                        }
                    }

                    .file-actions {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;

                        .file-status {
                            display: flex;
                            align-items: center;
                            gap: 4px;

                            .status-text {
                                font-size: 12px;
                                color: #666;
                            }

                            .success-icon {
                                color: #52c41a;
                                font-size: 14px;
                            }

                            .error-icon {
                                color: #ff4d4f;
                                font-size: 14px;
                            }
                        }

                        .action-buttons {
                            .van-button {
                                height: 28px;
                                font-size: 12px;
                                padding: 0 12px;

                                &--primary {
                                    background: #165dff;
                                    border-color: #165dff;
                                }

                                &--plain {
                                    color: #165dff;
                                    border-color: #165dff;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
</style>